Vue.component('c-tree', {
  template:`
  <el-tree
    ref="tree"
    :data="data"
    show-checkbox
    node-key="id"
    default-expand-all
    @check-change="sync"
    :check-on-click-node="true"
    :expand-on-click-node="false"
    >
  </el-tree>
  `,
  data() {
    return {

    }
  },
  props: {
    data: {
      default: []
    },

    value: {
      default: ""
    }
  },
  methods: {
    init(){
      this.check();
      window.t=this.$refs.tree;
    },
    check(){
      var res=[];
      if (this.value){
        if (typeof(this.value)=="string"){
          res=JSON.parse(this.value);
        }else{
          res=this.value;
        }
      }

      this.$refs.tree.setCheckedKeys(res);

    },
    sync(){
      var all=this.$refs.tree.getCheckedKeys();
      var res=[];
      for (var i in all) {
        if (all.hasOwnProperty(i)) {
          var t=all[i];
          if (t.startsWith("_id")) continue;
          res.push(t);
        }
      }
      this.$emit('input', JSON.stringify(res));
    }

  },
  watch: {

    value(newName, oldName){
      this.check();

    }
  },
  mounted(){
    var that=this;
    this.$nextTick(function () {
      that.init();
    });
  }

});
